﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DataMongo;
using Google.GData.Contacts;
using MongoDB.Bson;
using DataMongo.Entities;

using MVCMongo.Services;
using WebMatrix.WebData;

namespace MVCMongo.Controllers
{
    public class GroupWallPostController : ApiController
    {


        // GET api/WallPost
        public dynamic GetPosts(int groupid)
        {

            var connection = new RepositoryBaseMongo("UserPost");
            var pc = new RepositoryBaseMongo("PostComment");
            var friendlistconnection = new RepositoryBaseMongo("FriendList");
            var userconnection = new RepositoryBaseMongo("Users");
              var feedimageconnection = new RepositoryBaseMongo("FeedSourceDetail");
            var userid = WebSecurity.GetUserId(WebSecurity.CurrentUserName);

                
                var ret = (from post in connection.GetAll<Post>()
                             join userimage in userconnection.GetAll<Users>().ToList() on post.PostedBy equals userimage.UserId
                           join feedimage in feedimageconnection.GetAll<FeedSourceDetail>().ToList() on post.PostId equals feedimage.UserPostId into fi
                           from ft in fi.DefaultIfEmpty()
                           where post.GroupId == groupid
                           orderby post.PostedDate descending
                           select new
                           {
                               Message = post.Message,
                               PostedBy = post.PostedBy,
                               PostedByName = UtilityService.GetCurrentUserFullName(post.PostedBy),
                               PostedByAvatar = "/Content/UserProfile/User/" + userimage.ImageUrl,
                               PostedDate = post.PostedDate,
                               PostId = post.PostId,
                               Groupid=groupid,
                               LikeCount = post.LikeCount,
                               LinkThumbnailUrl = ft == null ? "" : ft.Embed,
                               PostComments = (from comment in pc.GetAll<PostComment>()
                                               join userimagecomment in userconnection.GetAll<Users>().ToList() on comment.CommentedBy equals userimagecomment.UserId

                                               where comment.PostId == post.PostId
                                              orderby comment.CommentedDate
                                              select new
                                              {
                                                  CommentedBy = comment.CommentedBy,
                                                  CommentedByName = UtilityService.GetCurrentUserFullName(comment.CommentedBy),
                                                  CommentedByAvatar = "/Content/UserProfile/User/" + userimagecomment.ImageUrl,
                                                  CommentedDate = comment.CommentedDate,
                                                  CommentId = comment.CommentId,
                                                  Message = comment.Message,
                                                  PostId = comment.PostId
                                                  
                                                  

                                              })
                           }).AsEnumerable();
                return ret; 
     


        }

        
        /*
        public Post GetPost(ObjectId _id)
        {
            var connection = new RepositoryBaseMongo("UserPost");

            var post = connection.Find<Post>(_id);
            if (post == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return post;
        }
        */


        public HttpResponseMessage PutPost(int id, Post post)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != post.PostId)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

         // POST api/WallPost
        public HttpResponseMessage PostPost(PostViewModel postViewModel)
        {
            
          
            var connection = new RepositoryBaseMongo("UserPost");

            int Id = 0;
            var sources = connection.GetAll<Post>().ToList();
            if (sources.Any())
                Id = sources.Max(x => x.PostId);
            Id += 1;
            postViewModel.Post.PostedBy = WebSecurity.GetUserId(WebSecurity.CurrentUserName);
            postViewModel.Post.PostedDate = DateTime.UtcNow;
            postViewModel.Post.PostId = Id;
            postViewModel.Post.GroupId = postViewModel.Post.GroupId;
            postViewModel.Post.Message = postViewModel.Post.Message;
            if (postViewModel.Source == "s")
            postViewModel.Post.Source = postViewModel.Source;
            else
            {
                postViewModel.Post.Source = "p";
            }
            connection.InsertOrUpdate(postViewModel.Post);
        if (postViewModel.Source=="s")
            {
                var connectFD = new RepositoryBaseMongo("FeedSourceDetail");
                var feedDetail = new FeedSourceDetail();
                feedDetail.UserPostId = Id;
                feedDetail.Body = postViewModel.FeedSourceDetail.Body;
                feedDetail.Title = postViewModel.FeedSourceDetail.Title;
             var path = AppDomain.CurrentDomain.BaseDirectory + "Content\\UserProfile\\PostShareImage\\";

                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);
                        var imagepath = AppDomain.CurrentDomain.BaseDirectory + "Content\\UserProfile\\PostShareImage\\" + UtilityService.RemoveSpecialCharacters(postViewModel.FeedSourceDetail.Title) + ".jpg";
                bool result = UtilityService.DownloadImageFromUrl(postViewModel.FeedSourceDetail.ImageUrl, imagepath);
                if (result)
                {
                    feedDetail.ImageUrl = UtilityService.RemoveSpecialCharacters(postViewModel.FeedSourceDetail.Title) + ".jpg";
  
                }
                feedDetail.Embed = postViewModel.FeedSourceDetail.Embed;
                connectFD.InsertOrUpdate(feedDetail);

            }
            var ret = new
            {
                Message = postViewModel.Post.Message,
                PostedBy = postViewModel.Post.PostedBy,
                PostedByName = UtilityService.GetCurrentUserFullName(postViewModel.Post.PostedBy),
                PostedByAvatar = "/Content/UserProfile/User/" + UtilityService.GetCurrentUserImage(postViewModel.Post.PostedBy),
                PostedDate = postViewModel.Post.PostedDate,
                PostId = postViewModel.Post.PostId,
                LikeCount = 0,
                LinkThumbnailUrl=postViewModel.Source== "s"?postViewModel.FeedSourceDetail.Embed :"",
            };
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ret);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = postViewModel.Post.PostId }));
            return response;
        }

        //public HttpResponseMessage PostPost(PostViewModel postViewModel)
        //{
        //    return null;
        //}
    }

}